<script setup lang="ts">
import { reactive, getCurrentInstance } from "vue";

import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import upload from "@iconify-icons/ep/upload";

import AppUtil from "@/utils/AppUtil";

import { useRoute } from "vue-router";

//import log from "./comp/log.vue";
import Form from "@/components/Form.vue";
import JSEncrypt from "jsencrypt";
const encryptStr = new JSEncrypt();

AppUtil.request(
  {
    url: "/api/v1/authentication/public-key",
    method: "get"
  },
  res => {
    // console.log('rsa', res);
    // state.key = res.data;
    // console.log("public-key", res.data);

    encryptStr.setPublicKey(res.data);
  }
);

defineOptions({
  name: "staff"
});
const config = reactive({
  listUrl: "/api/v1/users/users",
  addUrl: "/api/v1/users",
  editUrl: "/api/v1/users",
  deleteUrl: "/api/v1/users/delete",
  detailUrl: "",
  title: "员工",

  /**搜索条件 */
  searchForm: [
    //商品名称 goodsName
    {
      label: "昵称",
      prop: "nickName",
      type: "input",
      input: {
        type: "text"
      }
    },
    //条形码 barCode
    {
      label: "手机号",
      prop: "phone",
      type: "input",
      input: {
        type: "text"
      }
    }
  ],
  /**
   * 添加/编辑表单
   */
  editForm: [
    {
      label: "头像",
      prop: "avatar",
      type: "uploadOne",
      upload: {
        fileArr: []
      }
    },
    //名称     goodsName
    {
      label: "用户名",
      prop: "userName",
      type: "input",
      input: {
        type: "text"
      },
      span: 12,
      rules: [{ required: true, message: "请输入名称", trigger: "blur" }]
    },
    //昵称 nickName
    {
      label: "昵称",
      prop: "nickName",
      type: "input",
      input: {
        type: "text"
      },
      span: 12
    },
    //密码 password
    {
      label: "密码",
      prop: "password",
      type: "input",
      input: {
        type: "password"
      },
      span: 12
    },

    //生日 birth
    {
      label: "生日",
      prop: "birth",
      type: "date",
      date: {
        type: "date",
        format: "YYYY-MM-DD",
        valueFormat: "YYYY-MM-DD"
      },
      span: 12
    },
    //性别 sex
    {
      label: "性别",
      prop: "sex",
      type: "select",
      select: {
        options: [
          { label: "男", value: "0" },
          { label: "女", value: "1" }
        ]
      },
      value: "0",
      span: 12
    },
    //手机号 phone
    {
      label: "手机号",
      prop: "phone",
      type: "input",
      input: {
        type: "text"
      },
      span: 12
    },
    //邮箱 email
    {
      label: "邮箱",
      prop: "email",
      type: "input",
      input: {
        type: "text"
      },
      span: 12
    },
    //状态 status
    {
      label: "状态",
      prop: "status",
      type: "select",
      select: {
        options: [
          { label: "启用", value: "0" },
          { label: "禁用", value: "1" }
        ]
      },
      value: 0,
      rules: [{ required: true, message: "请选择状态", trigger: "blur" }],
      span: 12
    },
    {
      label: "所属角色",
      prop: "roleSids",
      type: "cascader",
      span: 12,
      cascader: {
        props: {
          checkStrictly: false,
          value: "roleKey",
          label: "roleName",
          children: "children",
          lazy: true,
          multiple: true,
          emitPath: false,
          lazyLoad(node, resolve) {
            const { level } = node;
            // console.log("node", node);
            if (level == 0) {
              //第一级，获取分类
              let arr = [];
              AppUtil.request(
                {
                  url: "/api/v1/roles/all"
                },
                res => {
                  pData.roleArr = arr = res.data;

                  check_leaf(arr);
                  function check_leaf(arr1: any[]) {
                    arr1.map(val => {
                      if (val.children && val.children.length > 0) {
                        check_leaf(val.children);
                      } else {
                        val.leaf = true;
                      }
                    });
                  }
                  resolve(arr);
                }
              );
            }
          }
        }
      }
    },
    //备注 note
    {
      label: "备注",
      prop: "note",
      type: "input",
      input: {
        type: "textarea",
        rows: 3
      },
      span: 24
    }
  ],
  rules: {},
  formData: {} as any,
  defaultData: {},

  /**
   * 表格列
   */
  columns: [
    {
      label: "头像",
      prop: "avatar",
      width: 160,
      slot: "avatar"
    },
    {
      label: "用户信息",
      prop: "userName",
      minWidth: 150,
      slot: "userName"
    },
    {
      label: "最近登陆",
      prop: "loginIp",
      minWidth: 160,
      slot: "login"
    },
    {
      label: "备注",
      prop: "note",
      minWidth: 100
    },
    // {
    //   label: "角色",
    //   prop: "roleNames",
    //   minWidth: 120
    // },
    {
      label: "创建时间",
      prop: "created",
      width: 150
    },
    {
      label: "状态",
      prop: "status",
      width: 80,
      slot: "status"
    },

    {
      label: "操作",
      prop: "action",
      width: 150,
      slot: "operation"
    }
  ]
});

const pData = reactive({
  /**
   * 表格数据
   */
  dataArr: [],
  /**
   * 表格加载
   */
  loading: false,
  /**请求中 */
  reqing: false,
  /**
   * 表格分页
   */
  pagination: {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  },

  imgArr: [],
  searchData: {},
  showEdit: false,
  /**
   * 分配线索弹窗
   */
  showDo: false,
  do: {
    ids: [],
    from: 2,
    yg_id: ""
  },

  id: "",
  // item: {},
  showStock: false,
  stock: {
    editForm: [
      // 门店 storeSid
      {
        label: "门店",
        prop: "storeSid",
        type: "select",
        select: {
          placeholder: "请选择门店",
          options: [],
          filterable: true,
          remote: true,
          loading: false,
          remoteMethod(query, val) {
            // console.log("remoteMethod", query, val);

            if (!val.options || !val.options.length) {
              val.select.loading = true;
              AppUtil.request(
                {
                  url: "/api/v1/stores",
                  method: "get"
                },
                (res: any) => {
                  res.data.records.map(item => {
                    item.value = item.sid;
                    item.name = item.storesName;
                  });
                  val.options = val.select.options = res.data.records;
                  // console.log("remoteMethod", res.data)
                },
                b => {
                  val.select.loading = false;
                }
              );
            } else if (query) {
              val.select.options = val.options.filter(val => {
                return val.name.includes(query);
              });
            } else {
              val.select.options = val.options;
            }
          }
        },
        rules: [
          {
            required: true,
            message: "请选择门店",
            trigger: "change"
          }
        ]
      },
      //库存 stock
      {
        label: "库存",
        prop: "stock",
        type: "input",
        input: {
          type: "number"
        },
        rules: [
          {
            validator: (rule: any, value: any, callback: any) => {
              if (value < 0) {
                return callback(new Error("库存必须大于等于0"));
              }
              callback();
            }
          }
        ]
      }
    ],
    formData: {} as any,
    defaultData: {}
  },
  /**角色列表 */
  roleArr: []

  //
});

const instance = getCurrentInstance();

function update_click(item) {
  console.log("update_click", item);
  config.formData = item;

  // config.editForm.map(item1 => {
  //   //处理封面初始化imgArr

  //   if (item1.type == "uploadOne") {
  //     item1.upload.fileArr = [
  //       {
  //         url: AppUtil.getAliImgUrlByH(item[item1.prop]),
  //         response: { code: 200, data: item[item1.prop] }
  //       }
  //     ];
  //   }
  // });

  AppUtil.request(
    {
      url: "/api/v1/users/" + item.sid,
      method: "get"
    },
    res => {
      // console.log("详情", res);
      res.data.status = res.data.status + "";
      config.formData = res.data;
      config.formData.sid = item.sid;
      config.formData.sex = config.formData.sex + "";
      config.editForm.map(item1 => {
        //处理封面初始化imgArr

        if (item1.type == "uploadOne") {
          if (res.data[item1.prop]) {
            item1.upload.fileArr = [
              {
                url: AppUtil.getAliImgUrlByH(res.data[item1.prop]),
                response: {
                  code: 200,
                  data: {
                    url: res.data[item1.prop]
                  }
                }
              }
            ];
          } else {
            item1.upload.fileArr = [];
          }
        } else if (item1.prop == "roleSids") {
          config.formData[item1.prop] = res.data.roleKeySet;
          // if (strArr.length > 0) {
          //   item1.cascader.placeholder = strArr.join(",");
          // }
        }
      });
    }
  );

  pData.showEdit = true;
}
function add_click() {
  if (config.formData.sid) {
    //移除选中的编辑数据，保留上次新增数据
    config.formData = JSON.parse(JSON.stringify(config.defaultData));
  }

  config.editForm.map(item1 => {
    //处理封面初始化imgArr
    if (item1.type == "uploadOne" || item1.type == "uploads") {
      item1.upload.fileArr = [];
    }
  });
  // config.editForm=JSON.parse(JSON.stringify(config.editForm));
  pData.showEdit = true;
}

function handleSizeChange(val: number) {
  console.log(`${val} items per page`);
  pData.pagination.pageSize = val;
  reset_list();
}

function handleCurrentChange(val: number) {
  console.log(`current page: ${val}`);
  pData.pagination.currentPage = val;
  onSearch();
}
//请求轮播图数据
async function onSearch() {
  pData.loading = true;

  AppUtil.request(
    {
      url: config.listUrl,
      method: "get",
      params: {
        ...pData.searchData,
        current: pData.pagination.currentPage,
        size: pData.pagination.pageSize
      }
    },
    res => {
      // console.log("onSearch", res);

      // res.data.records.map(item => {

      // });
      pData.dataArr = res.data.records;
      pData.pagination.total = res.data.total * 1;
      pData.pagination.currentPage = res.data.current * 1;
    },
    b => (pData.loading = false)
  );
}
onSearch();

function handleDelete(item) {
  AppUtil.request(
    {
      url: config.deleteUrl,
      method: "PUT",
      data: {
        sidList: [item.sid]
      }
    },
    res => {
      onSearch();
    }
  );
}

function search_click() {
  reset_list();
}
/**搜索第一页的数据 */
function reset_list() {
  pData.pagination.currentPage = 1;
  onSearch();
}
function submitForm() {
  submit_form();
  // if (pData.imgArr.length < 1) {
  //   return instance.proxy.$alert("请选择图片");
  // }
  // let img = pData.imgArr[0];
  // //图片已经上传过
  // if (img.response && img.response.code == 200) {
  //   return submit_form();
  // }
  // //上传图片
  // upload1.value!.submit();
}
/**
 * 提交表单
 */
function submit_form() {
  instance.proxy.$refs["vForm"].validate(valid => {
    if (!valid) return;
    pData.reqing = true;

    // return console.log("formData", config.formData);
    //config.formData 移除sid
    let formData: any = JSON.parse(JSON.stringify(config.formData));
    delete formData.sid;

    // formData.label = lArr;
    formData.password &&
      (formData.password = encryptStr.encrypt(formData.password));
    AppUtil.request(
      {
        url: config.formData.sid
          ? config.editUrl + "/" + config.formData.sid
          : config.addUrl,

        method: config.formData.sid ? "put" : "post",
        // url: config.addUrl,
        // method: "post",
        // data: formData
        data: {
          avatar: formData.avatar,
          birth: formData.birth,
          userName: formData.userName,
          password: formData.password,
          nickname: formData.nickname,
          email: formData.email,
          phone: formData.phone,
          roleSids: get_role_sid(formData.roleSids),
          status: formData.status,
          note: formData.note,
          sex: formData.sex
        }
      },
      res => {
        // console.log("banner", res);
        instance.proxy.$message.success(
          config.formData.sid ? "修改成功" : "添加成功"
        );
        onSearch();
        pData.showEdit = false;
      },
      b => {
        pData.reqing = false;
      }
    );
  });
}
function get_role_sid(roleSids = []) {
  let arr = [];
  pData.roleArr.map(item => {
    if (roleSids.includes(item.roleKey)) {
      arr.push(item.sid);
    }
  });
  return arr;
}
</script>

<template>
  <div class="main">
    <el-form
      v-if="config.searchForm && config.searchForm.length > 0"
      :model="pData.searchData"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
      style="padding-bottom: 5px"
      :inline="true"
    >
      <el-form-item
        v-for="(item, i) in config.searchForm"
        :key="i"
        :label="item.label"
        :prop="item.prop"
      >
        <el-select
          v-if="item.type === 'select'"
          v-model="pData.searchData[item.prop]"
          style="width: 200px"
          placeholder="请选择"
        >
          <el-option
            v-for="(option, j) in item.options"
            :key="j"
            :label="option.label || option.name"
            :value="option.value || option.id"
          />
        </el-select>
        <el-input
          v-else-if="item.type === 'input'"
          v-model="pData.searchData[item.prop]"
          :placeholder="item.input.placeholder"
          clearable
        />
        <el-date-picker
          v-else-if="item.type === 'datetimerange'"
          v-model="pData.searchData[item.prop]"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 360px"
        />
        <el-cascader
          v-else-if="item.type === 'cascader'"
          v-model="pData.searchData[item.prop]"
          style="width: 100%"
          :props="item.cascader.props"
          :options="item.cascader.options"
          clearable
          :placeholder="item.cascader.placeholder"
          :show-all-levels="item.cascader.showAllLevels || false"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="pData.loading"
          @click="search_click"
        >
          搜索
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar
      :title="config.title + '管理'"
      :columns="config.columns"
      @refresh="onSearch"
    >
      <template #buttons>
        <el-button
          v-if="config.addUrl"
          type="primary"
          :icon="useRenderIcon(upload)"
          @click="add_click"
        >
          新增{{ config.title }}
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          :data="pData.dataArr"
          :columns="dynamicColumns"
          :loading="pData.loading"
          :size="size"
          :pagination="pData.pagination"
          :paginationSmall="size === 'small' ? true : false"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #avatar="{ row }">
            <el-image
              style="width: 120px; height: 120px"
              fit="cover"
              :src="AppUtil.getAliImgUrlByW(row.avatar, 200)"
            />
          </template>
          <template #userName="{ row }">
            <!-- <div style="font-weight: bold">{{ row.goodsName }}</div> -->
            <div>用户名：{{ row.userName }}</div>
            <div>昵称：{{ row.nickName }}</div>
            <div>手机号：{{ row.phone }}</div>
            <div v-if="row.belongStore">所属门店：{{ row.belongStore }}</div>
            <!-- <div>烟碱总量：{{ row.totalNicotine }}</div>
            <div>烟碱浓度：{{ row.densityNicotine }}</div> -->
          </template>
          <template #login="{ row }">
            <div>登陆IP：{{ row.loginIp }}</div>
            <div>登陆时间：{{ row.loginTime }}</div>
          </template>
          <template #status="{ row }">
            <div style="margin-top: 5px">
              <el-tag
                :type="row.status == 0 ? 'success' : 'danger'"
                size="small"
              >
                {{ row.status == 0 ? "正常" : "禁用" }}
              </el-tag>
            </div>
          </template>
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              @click="update_click(row)"
            >
              修改
            </el-button>

            <el-popconfirm
              :title="`是否确认删除这条数据`"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <el-dialog
      v-model="pData.showEdit"
      align-center
      :title="`${config.formData.sid ? '修改' : '新增'}${config.title}`"
      :width="700"
      draggable
    >
      <div style="max-height: 82vh; overflow-y: auto; padding-right: 1.5rem">
        <Form ref="vForm" v-model="config" />
      </div>

      <template #footer>
        <div class="cls-center">
          <el-button @click="pData.showEdit = false">取消</el-button>
          <el-button
            type="primary"
            :loading="pData.reqing"
            @click="submitForm()"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <el-dialog
      v-model="pData.showStock"
      align-center
      title="录入库存"
      width="600px"
      draggable
    >
      <div style="max-height: 82vh; overflow-y: auto; padding-right: 1.5rem">
        <Form ref="sForm" v-model="pData.stock" />
      </div>
      <template #footer>
        <div class="cls-center">
          <el-button
            type="primary"
            :loading="pData.reqing"
            @click="submitStockForm()"
          >
            确定
          </el-button>
          <el-button @click="pData.showStock = false">关闭</el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
